package com.padgett.resourcemanagement.service;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Save client.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxSaveServiceServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxSaveServiceServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String serviceId=req.getParameter("serviceId");
		String type=req.getParameter("Type");
		String dueDateString=req.getParameter("DueDate");
		String fee=req.getParameter("Fee");
		String billableString=req.getParameter("Billable");
		String accountant=req.getParameter("Accountant");
		String note=req.getParameter("Note");
		// Client Number and Legal Number must be presented to generate a unique key
		UserService userService=UserServiceFactory.getUserService();
		User user=userService.getCurrentUser();
		Key key=KeyFactory.stringToKey(serviceId);
		Entity service=ClientDAO.loadEntity(key);
		service.setProperty("LastModifiedBy", user.getNickname());
		service.setProperty("LastModifiedDate", new Date(System.currentTimeMillis()));
		
		service.setProperty("Type", type);
		service.setUnindexedProperty("Fee", Double.parseDouble(fee));
		boolean billable=(billableString.equalsIgnoreCase("true")?true:false);
		service.setProperty("Billable", billable);
		service.setProperty("Accountant", accountant);
		Date dueDate=null;
		if(dueDateString!=null&&!dueDateString.isEmpty()){
			dueDate=new Date(Long.parseLong(dueDateString));
			service.setProperty("DueDate", dueDate);
		}
		if(note!=null){
			service.setUnindexedProperty("Note", new Text(note));
		}
		Key savedKey=ClientDAO.saveEntity(service);
		JSONObject response=new JSONObject();
		try {
			if(savedKey!=null){
				response.put("success", "true");
				response.put("serviceId", KeyFactory.keyToString(savedKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save client at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
		}
		resp.getWriter().write(response.toString());
	}

}
